﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.IO;
namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Socket socketSend;
        private void ShowMessage(string msgStr)
        {
            txtLog.AppendText(msgStr + "\r\n");
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                //当开始点击连接时，在服务器端创建一个负责连接的IP地址和端口号           
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse(txtServer.Text);
                //创建端口号对象
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
                //获取连接的远程服务器的应用程序的IP地址和端口号
                socketSend.Connect(point);
                ShowMessage("连接" + ip + ":" + txtPort.Text.Trim() + " 成功！");
                //开启新线程不停接收服务器发送过来的消息
                Thread th = new Thread(Receive);
                th.IsBackground = true;
                th.Start();
            }
            catch
            {
                MessageBox.Show("网络连接错误，请重新连入！");
            }
        }
        /// <summary>
        /// 给服务端发送文本消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 


        /// <summary>
        /// 不停接收服务器端的消息
        /// </summary>
        private void btnSend_Click(object sender, EventArgs e)
        {
            //如果socket未连接，则退出
            if (socketSend == null || !socketSend.Connected)
            {
                MessageBox.Show("网络连接错误，请重新连入！");
                return;
            }

            try
            {
                var str = txtMag.Text;
                byte[] buffer = Encoding.UTF8.GetBytes(str);
                socketSend.Send(buffer);
                //发送成功后清空文本框
                txtMag.Text = string.Empty;
            }
            catch
            {
                MessageBox.Show("网络连接错误，请重新连入！");
            }

        }

        private void Receive()
        {
            while (true)
            {
                byte[] buffer = new Byte[1024 * 1024 * 20];
                //实际接收的有效字节数
                int r = socketSend.Receive(buffer);
                //指导字节数读取完成，跳出循环
                if (r == 0)
                {
                    break;
                }
                //表示发送文字
                if (buffer[0] == 0)
                {
                    string str = Encoding.UTF8.GetString(buffer, 1, r - 1);
                    ShowMessage(socketSend.RemoteEndPoint + ":" + str);
                }

                //表示发送文件
                else if (buffer[0] == 1)
                {
                    var dialog = new SaveFileDialog();
                    dialog.InitialDirectory = @"D:\CsharpAdvanced\tt";
                    dialog.Title = "请选择保存的文件夹！";
                    dialog.Filter = "所有文件夹|*.*";
                    dialog.ShowDialog(this);

                    var path = dialog.FileName;

                    if (string.IsNullOrEmpty(path))
                    {
                        MessageBox.Show("请选择文件夹！");
                        return;
                    }

                    try
                    {
                        using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            fsWrite.Write(buffer, 1, r - 1);
                        }
                        ShowMessage(socketSend.RemoteEndPoint + ":文件发送成功！");
                    }
                    catch
                    {
                        MessageBox.Show("网络访问错误，请重试！");
                        ShowMessage(socketSend.RemoteEndPoint + ":文件发送失败！");
                    }
                }

                //表示震动
                else if (buffer[0] == 2)
                {
                    //调用震动方法
                    Shake();
                }

            }

        }
        /// <summary>
        /// 窗体震动
        /// </summary>

        private void Shake()
        {
            //原窗体的X坐标
            var x = this.Location.X;
            var y = this.Location.Y;

            //上下移动450次
            for(var i=0;i<450;i++)
            {
                this.Location= new Point(x - 20, y - 20);
                this.Location = new Point(x + 20, y +20);
            }
            //移动完成回到原来位置
            this.Location = new Point(x,y);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }
    }
}
